package com.rjpacket.supernews.app.adapters;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.v4.view.PagerAdapter;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
import com.rjpacket.supernews.app.R;
import com.rjpacket.supernews.app.models.RecycleCategory;
import com.rjpacket.supernews.app.utils.HttpTool;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * Created by Administrator on 2015/3/16 0016.
 */
//显示图片
public class ImageViewPager extends PagerAdapter {

    private List<String> list;

    private Bitmap bmp;

    private Context context;

    public ImageViewPager(Context context, List<String> list) {

        this.context = context;

        this.list = list;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object o) {
        return view == o;
    }


    private ImageView imageView = null;

    @Override
    public Object instantiateItem(ViewGroup container, int position) {

        ImageView ret = new ImageView(context);

        String s = list.get(position);

        Task task = new Task();

        task.execute(s);

        imageView = ret;

        imageView.setTag(s);

        container.addView(ret);

        return ret;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {

        if (container != null && object != null) {

            container.removeView((View) object);
        }
    }

    private class Task extends AsyncTask<String, Integer, Bitmap> {

        private String reqUrl;

        @Override
        protected Bitmap doInBackground(String... params) {
            Bitmap ret = null;

            if (params != null && params.length > 0) {

                String url = params[0];

                String fileName = null;

                reqUrl = url;

                try {

                    // 使用MD5将网址转换为一个特定的唯一的文件名，来进行检查
                    MessageDigest md5 = MessageDigest.getInstance("MD5");

                    byte[] bytes = md5.digest(reqUrl.getBytes());

                    fileName = toHex(bytes);

                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                }

                // 判断本地是否存在图片，存在就直接返回Bitmap，不存在，才联网

                Bitmap cacheBitmap = null;

                String state = Environment.getExternalStorageState();

                if (Environment.MEDIA_MOUNTED.equals(state)) {
                    File sdcard = Environment.getExternalStorageDirectory();

                    File folder = new File(sdcard, "MyImages");

                    File targetFile = new File(folder, fileName);

                    if (targetFile.exists()) {
                        cacheBitmap = BitmapFactory.decodeFile(targetFile.getAbsolutePath());
                    }

                }

                if (cacheBitmap == null) {

                    Log.d("------", "network");

                    HttpGet request = new HttpGet(url);

                    HttpClient client = new DefaultHttpClient();

                    try {
                        HttpResponse response = client.execute(request);
                        StatusLine statusLine = response.getStatusLine();

                        int statusCode = statusLine.getStatusCode();

                        if (statusCode == 200) {
                            HttpEntity entity = response.getEntity();

                            byte[] bytes = EntityUtils.toByteArray(entity);

                            state = Environment.getExternalStorageState();
                            if (Environment.MEDIA_MOUNTED.equals(state)) {
                                File sdcard = Environment.getExternalStorageDirectory();

                                File folder = new File(sdcard, "MyImages");
                                if (!folder.exists()) {
                                    folder.mkdir();
                                }

                                File targetFile = new File(folder, fileName);

                                // 写缓存文件，利用targetFile输出字节数组

                                if (!targetFile.exists()) {
                                    targetFile.createNewFile();
                                }

                                FileOutputStream fout = new FileOutputStream(targetFile);

                                fout.write(bytes);

                                fout.close();

                            }

                            ret = bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                } else {
                    ret = bmp = cacheBitmap;
                }
            }
            return ret;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {

            if (imageView.getTag() == null) {
                imageView.setImageBitmap(bitmap);
            } else {
                if (imageView.getTag().equals(reqUrl)) {
                    imageView.setImageBitmap(bitmap);
                } else {

                }
            }

        }
    }


    private static String toHex(byte[] data) {
        String ret = "";

        StringBuilder sb = new StringBuilder();

        for (byte b : data) {

            if (b > 0 && b < 16) {
                sb.append('0');
            }
            sb.append(Integer.toHexString(b));
        }

        ret = sb.toString();

        return ret;
    }
}
